package cn.itcast.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController{

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpSession session;
    @Autowired
    protected UserService userService;
    @Autowired
    protected ModuleService moduleService;

/*	@RequestMapping("/login")
	public String login(String email,String password) {
 	    1、判断email和password是否为空
//        2、 select  * from pe_user where email=?? and password=??
        2、只是先根据邮箱查询用户  select  * from pe_user where email=??
         如果用户为空代表邮箱错误
         如果用户不为空，判断密码
                     如果密码不一样，代表密码错误
                     如果密码一样，代表登录成功，把用户放到session中

//        1、判断email和password是否为空
      if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){
          request.setAttribute("error","邮箱或密码不能为空");
          return "forward:/login.jsp";
      }
//    2、只是先根据邮箱查询用户
       User user = userService.findByEmail(email);
//        如果用户为空代表邮箱错误
        if(user==null){
            request.setAttribute("error","邮箱错误");
            return "forward:/login.jsp";
        }else{
//            判断密码时先把页面传过来的明文加密
            String password_page = new Md5Hash(password,email,2).toString();
            String password_db = user.getPassword();
            if(!password_page.equals(password_db)){
                request.setAttribute("error","密码错误");
                return "forward:/login.jsp";
            }
        }

//        动态获取登录人的菜单
        List<Module> moduleList  =  moduleService.findModuleListBy(user);
        session.setAttribute("modules",moduleList);


//        把当前登录人放到session中
        session.setAttribute("loginUser",user); //注意这里的名称一定要写loginUser
        return "home/main";
	}*/

    @RequestMapping("/login")
    public String login(String email,String password) {
/*	    1、判断email和password是否为空
//        2、 select  * from pe_user where email=?? and password=??
        2、只是先根据邮箱查询用户  select  * from pe_user where email=??
         如果用户为空代表邮箱错误
         如果用户不为空，判断密码
                     如果密码不一样，代表密码错误
                     如果密码一样，代表登录成功，把用户放到session中*/

//        1、判断email和password是否为空
        if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){
            request.setAttribute("error","邮箱或密码不能为空");
            return "forward:/login.jsp";
        }



//        如果使用shiro的登录（认证）有三个步骤：1、创建令牌 2、获取主题Subject 3、开始认证


//       1、创建令牌  这里存放的密码一定要加密
        UsernamePasswordToken token = new UsernamePasswordToken(email,new Md5Hash(password,email,2).toString());
//        2、获取主题Subject
        Subject subject = SecurityUtils.getSubject();
        try {
//        3、开始认证
            subject.login(token); //AuthenticationToken
        } catch (AuthenticationException e) {
            request.setAttribute("error","邮箱或密码不正确");
            return "forward:/login.jsp";
        }


//        动态获取登录人的菜单
        User user = (User) subject.getPrincipal();
        List<Module> moduleList  =  moduleService.findModuleListBy(user);
        session.setAttribute("modules",moduleList);

//        把当前登录人放到session中
        session.setAttribute("loginUser",user); //注意这里的名称一定要写loginUser
        return "home/main";
    }


    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){
//        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();  //登出

        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
	    return "home/home";
    }
}
